package rs.udd.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.envers.Audited;
import org.hibernate.validator.constraints.NotBlank;

@Audited
@Entity
@Table(name = "UDD_KEY_WORDS")
public class KeyWord extends AbstractEntity {

	private static final long serialVersionUID = 5009210726393566262L;

	@NotBlank
	@Column(unique = true)
	private String word;

	@NotNull
	@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }, mappedBy = "keyWords") // initiated by Advert
	private Set<Advert> adverts = new HashSet<Advert>();

	public KeyWord() {

	}

	public String getWord() {
		return word;
	}

	public void setWord(String word) {
		this.word = word;
	}

	public Set<Advert> getAdverts() {
		return adverts;
	}

	public void setAdverts(Set<Advert> adverts) {
		this.adverts = adverts;
	}

	@Override
	public int hashCode() {

		return new HashCodeBuilder()
				.appendSuper(super.hashCode())
				.append(word)
				.hashCode();
	}

	@Override
	public boolean equals(Object obj) {

		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj.getClass() != getClass()) {
			return false;
		}

		final KeyWord otherKeyWord = (KeyWord) obj;

		return new EqualsBuilder()
				.appendSuper(super.equals(obj))
				.append(word, otherKeyWord.getWord())
				.isEquals();
	}

	@Override
	public String toString() {

		return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
				.append(super.toString())
				.append("word", word)
				.toString();
	}

}
